package util

import (
	"errors"
	"github.com/golang-jwt/jwt"
	"svs/global"
	"svs/model/request"
	"time"
)

var (
	TokenExpired     = errors.New("Token is expired")
	TokenNotValidYet = errors.New("Token not active yet")
	TokenMalformed   = errors.New("token format is error")
	TokenInvalid     = errors.New("token is invalid")
)

type JWT struct {
	SigningKey []byte
}

func NewJwt() *JWT {
	return &JWT{SigningKey: []byte(global.CONFIG.Jwt.SigningKey)}
}

// 解析token
func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return j.SigningKey, nil
	})

	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil {
		if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
			return claims, nil
		}
		return nil, TokenInvalid
	} else {
		return nil, TokenInvalid
	}
}

func (j *JWT) CreateClaims(claims request.BaseClaims) request.CustomClaims {
	return request.CustomClaims{
		BaseClaims: claims,
		BufferTime: global.CONFIG.Jwt.BufferTime,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + global.CONFIG.Jwt.ExpiresTime,
			Issuer:    global.CONFIG.Jwt.Issuer,
		},
	}
}

func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(j.SigningKey)
}

// 设置缓存时间为1s，1s后缓存失效
func (j *JWT) DestroyClaims(token string) {
	global.CACHE.SetWithExpire(token, "1", time.Second)
}
